package com.clkj.mobileinspector.ui.fragment;

import android.graphics.Color;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.clkj.mobileinspector.R;
import com.clkj.mobileinspector.model.Constant;
import com.clkj.mobileinspector.model.ObserverOnNext;
import com.clkj.mobileinspector.model.OkHttpUtils;
import com.clkj.mobileinspector.model.bean.PolicedeptBean;
import com.clkj.mobileinspector.model.bean.QueryBean;
import com.clkj.mobileinspector.model.bean.QuerySuccessBean;
import com.clkj.mobileinspector.model.bean.ResourceApi;
import com.clkj.mobileinspector.ui.activity.MainActivity;
import com.clkj.mobileinspector.ui.activity.StatisticsActivity;
import com.clkj.mobileinspector.utils.JsonUtils;
import com.clkj.mobileinspector.utils.LogUtils;
import com.clkj.mobileinspector.utils.ResourceApiUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.reflect.TypeToken;
import com.lws.basic.base.BaseFragment;
import com.lws.basic.utils.common.GsonUtils;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.TimeUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.clkj.mobileinspector.utils.JsonUtils.queryGetFiled;

/**
 * @author 松
 * 2020/10/7 10:49
 * 月度分析
 */
public class MonthlyAnalysisFragment extends BaseFragment {
    @BindView(R.id.et_start)
    EditText mEtStart;
    @BindView(R.id.et_end)
    EditText mEtEnd;
    @BindView(R.id.sp_unit)
    Spinner mSpUnit;
    @BindView(R.id.sp_local)
    Spinner mSpLocal;
    @BindView(R.id.lineChart)
    LineChart mLineChart;
    Unbinder mUnbinder;
    private String mPolicedepId;//局id
    private String mChild;//所id
    private List<PolicedeptBean.ChildBean> mChildBeanList;

    @Override
    public int setLayoutId() {
        return R.layout.fragment_monthly_analysis;
    }


    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        mUnbinder = ButterKnife.bind(this, rootView);
    }

    @Override
    protected void initData() {
        super.initData();
        initSpinner(((StatisticsActivity) getActivity()).getSpList());
        getData(search());
    }

    /**
     * 初始化下拉列表
     */
    private void initSpinner(List<QuerySuccessBean.DataBean.DataListBean.FieldValuesBean> list) {
        try {


            //局
            String policedept = JsonUtils.queryGetFiled(list, "policedept");
            Type policedeptType = new TypeToken<List<PolicedeptBean>>() {
            }.getType();
            List<PolicedeptBean> policedeptBeanList = GsonUtils.getInstance().fromJson(policedept, policedeptType);
            List<String> policedeptList = new ArrayList<>();
            policedeptList.add("全部");
            for (PolicedeptBean bean : policedeptBeanList) {
                policedeptList.add(bean.getName());
            }
            mPolicedepId = "0";
            //所
            mChildBeanList = new ArrayList<>();
            List<String> childList = new ArrayList<>();
            childList.add("全部");

            mChild = "0";
            ArrayAdapter adapterLocal = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, childList);
            mSpLocal.setAdapter(adapterLocal);
            mSpLocal.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position == 0) {
                        mChild = "0";
                    } else {
                        mChild = mChildBeanList.get(position - 1).getDeptid() + "";
                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            //局
            ArrayAdapter adapterUnit = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, policedeptList);
            mSpUnit.setAdapter(adapterUnit);
            mSpUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    List<String> childList = new ArrayList<>();
                    childList.add("全部");
                    mChild = "0";
                    adapterLocal.clear();
                    if (position == 0) {
                        mPolicedepId = "0";

                    } else {
                        mPolicedepId = policedeptBeanList.get(position - 1).getDeptid() + "";
                        mChildBeanList = policedeptBeanList.get(position - 1).getChild();
                        for (PolicedeptBean.ChildBean bean : policedeptBeanList.get(position - 1).getChild()) {
                            childList.add(bean.getName());
                        }

                    }
                    adapterLocal.addAll(childList);


                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        } catch (Exception e) {
            MyToast.show(e.getMessage());
            MyLogger.i("统计分析下拉列表" + e.getMessage());
        }


    }

    /**
     * 获取数据
     */
    private void getData(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {
        ResourceApi monthContrastChart = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.monthContrastChart);


        showLoading();
        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();
//        QueryBean.ParameterBean.OrderByBean order1 = new QueryBean.ParameterBean.OrderByBean();
//        order1.setSort("passdate");
//        order1.setSort("desc");
//        orderByList.add(order1);

        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(1000);

        String json = JsonUtils.query(keyValueListBeanList, "month,inspectiontotal"
                , monthContrastChart.getResourceId(), orderByList, page, monthContrastChart.getResourceRegionalismCode());
        LogUtils.logUpload("月度分析", "1", monthContrastChart.getResourceId(), monthContrastChart.getResourceAddress(), json, "", "成功", "","");

        OkHttpUtils.post(monthContrastChart.getResourceAddress(), json, QuerySuccessBean.class).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {
                dismissLoading();

                if (querySuccessBean.getCode().equals("200")) {
                    initLineChart(querySuccessBean.getData().getDataList());
                } else {
                    MyToast.show(querySuccessBean.getMessage());
                }
            }
        });
    }


    /**
     * 搜索条件
     */
    private List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> search() {
        String start = mEtStart.getText().toString();//
        String end = mEtEnd.getText().toString();//
        if (!TextUtils.isEmpty(end)){
            end+=" 23:59:59";
        }
        List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> list = new ArrayList<>();

        if (!mPolicedepId.equals("0")) {
            QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean2 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
            bean2.setKey("firstleveldutyunit");
            bean2.setRelationOperator("=");
            bean2.setValue(mPolicedepId);
            list.add(bean2);
        }
        if (!mChild.equals("0")) {
            QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
            bean.setKey("secondleveldutyunit");
            bean.setRelationOperator("=");
            bean.setValue(mChild);
            list.add(bean);
        }
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean3 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean3.setKey("starttime");
        bean3.setRelationOperator(">=");
        bean3.setValue(start);
        list.add(bean3);
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean4 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean4.setKey("endtime");
        bean4.setRelationOperator("<=");
        bean4.setValue(end);
        list.add(bean4);
        return list;
    }



    /**
     * 线型图
     */
    private void initLineChart(List<QuerySuccessBean.DataBean.DataListBean> list) {
        try {



            List<Integer> numList = new ArrayList<>();
            List<String> month = new ArrayList<>();
            int number =0;
            for (int i = 0; i < list.size(); i++) {
                try {


                    String m = queryGetFiled(list.get(i).getFieldValues(), "month");
                    m = m.substring(m.length() - 2);
                    MyLogger.i(m);
                    month.add(m);
                    if (TextUtils.isEmpty(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal"))) {
                        numList.add(0);

                    } else {
                        numList.add(Integer.valueOf(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal")));
                    }
                    if (number < Integer.valueOf(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal"))) {
                        number = Integer.valueOf(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal"));
                    }
                }catch (Exception e){
                    MyLogger.i("月份"+e.getMessage());
                }

            }

            if (number <= 10) {
                number = 10;
            } else if (number > 10 && number <= 100) {
                if (number!=100){
                    String decade = (number+"").substring(0,1);
                    number = Integer.valueOf( ((Integer.valueOf(decade)+1)+"0"));
                }
            } else if (number > 100 && number <= 1000) {
                if (number!=1000){
                    String decade = (number+"").substring(0,1);
                    number = Integer.valueOf( ((Integer.valueOf(decade)+1)+"00"));
                }
            } else {

            }

            XAxis xAxis;
            YAxis leftAxis = mLineChart.getAxisLeft();   //Y左
            YAxis rightAxis = mLineChart.getAxisRight();  //Y右
            xAxis = mLineChart.getXAxis();  //x轴

            // lineChart.setDrawBorders(false);//显示边界
            rightAxis.setEnabled(false); //不显示y轴右边的值

            //折线图例 标签 设置
            Legend legend = mLineChart.getLegend();
            legend.setForm(Legend.LegendForm.LINE);
            legend.setTextSize(12);
            //显示位置
            legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
            legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
            legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
            legend.setDrawInside(false);
            xAxis.setDrawLabels(true);


            xAxis.setDrawAxisLine(true);//显示X轴
            //X轴设置显示位置在底部
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setGranularity(1f);
            xAxis.setLabelCount(list.size());
            xAxis.setDrawGridLines(false); //关闭x轴 网络格线

            leftAxis.setAxisMaximum(number);
            leftAxis.setAxisMinimum(0);


            //保证Y轴从0开始，不然会上移一点
            leftAxis.setAxisMinimum(0f);
            rightAxis.setAxisMinimum(0f);


            mLineChart.getDescription().setEnabled(false); //不显示描述文字

            mLineChart.setDragEnabled(true);
            List<Entry> entries = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                entries.add(new Entry(i,  numList.get(i)));

            }
            //格式化 X轴下方文字
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                        try {
                            return month.get((int) value);
                        }catch (Exception e){
                            MyLogger.i(e.getMessage());
                            return "";
                        }


                }

            });


            LineDataSet lineDataSet = new LineDataSet(entries, "月度分析");
            lineDataSet.setColor(getResources().getColor(R.color.yellow_ff7500));
            lineDataSet.setLineWidth(1.5f);
            lineDataSet.setCircleRadius(1.5f);
            lineDataSet.setColor(getResources().getColor(R.color.yellow_ff7500));
            lineDataSet.setDrawCircleHole(false);
            lineDataSet.setCircleColor(Color.RED);    //圆点颜色
            lineDataSet.setHighLightColor(getResources().getColor(R.color.yellow_ff7500));
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
            lineDataSet.setValueTextSize(10);  //数值大小
            lineDataSet.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return ((int)value)+"";
                }
            });
            LineData lineData = new LineData(lineDataSet);
            mLineChart.setData(lineData);
            mLineChart.invalidate();
        }catch (Exception e){
            MyLogger.i(e.getMessage());
        }


    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    @OnClick({R.id.et_start, R.id.et_end, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_start:
                showTime(1);
                break;
            case R.id.et_end:
                showTime(2);
                break;
            case R.id.btn_search:
                getData(search());
                break;
        }
    }

    /**
     * 显示时间
     */
    private void showTime(int flag) {
        TimePickerView pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = TimeUtils.date2date(date);
                //1开始时间
                if (flag == 1) {
                    mEtStart.setText(time);
                }
                //结束时间
                if (flag == 2) {
                    mEtEnd.setText(time);
                }

                MyLogger.i(TimeUtils.date2date(date));

            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setBgColor(0xffd6ecf0)
                .setTitleBgColor(0xffd6ecf0)
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();

        pvTime.show();
    }
}
